package com.xnx3.banmahuishou.core.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.xnx3.DateUtil;
import com.xnx3.j2ee.Global;
import com.xnx3.net.HttpResponse;
import com.xnx3.net.HttpUtil;


public class AppUtil {


	public static String getRandomCode(int length) {
		StringBuffer sBuffer = new StringBuffer("");
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			sBuffer.append(random.nextInt(10));
		}
		return  sBuffer.toString();
	}

	public static Integer getMonthBegin(Date date) {
		Calendar c = Calendar.getInstance();

		c.setTime(date);
		//设置为1号,当前日期既为本月第一天  
		c.set(Calendar.DAY_OF_MONTH, 1);
		//将小时至0  
		c.set(Calendar.HOUR_OF_DAY, 0);  
		//将分钟至0  
		c.set(Calendar.MINUTE, 0);  
		//将秒至0  
		c.set(Calendar.SECOND,0);  
		//将毫秒至0  
		c.set(Calendar.MILLISECOND, 0);  
		// 获取本月第一天的十位时间戳  
		Integer tenInteger= DateUtil.long13To10(c.getTimeInMillis());
		return tenInteger;  
	}
	/**
	 * 获取需要减去天数回到周一
	 * @author 关光礼
	 * @return 周一 0 周二 1 .. 周日 6；
	 */
	public static int getcurrentWeek() {

		int dayInt = DateUtil.currentWeek();
		if(dayInt == 1) {
			return 6;
		}
		if(dayInt == 2) {
			return 0;
		}
		if(dayInt == 3) {
			return 1;
		}
		if(dayInt == 4) {
			return 2;
		}
		if(dayInt == 5) {
			return 3;
		}
		if(dayInt == 6) {
			return 4;
		}
		if(dayInt == 7) {
			return 5;
		}
		return 0;
	}


	/**
	 * 获取当前当月1号零时的时间戳
	 * @author 李鑫
	 * @return 
	 */
	public static long getMonthBegin4Linux() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		long timeInMillis = calendar.getTimeInMillis();
		return timeInMillis / 1000;
	}

	/**
	 * 获取当周周一零时的时间戳
	 * @author 李鑫
	 * @return 
	 */
	public static long getWeekBegin4Linux() {
		Calendar cal = Calendar.getInstance();
		int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 1;

		if (day_of_week == 0) {
			day_of_week = 7;
		}

		cal.add(Calendar.DATE, -day_of_week + 1);

		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);


		return cal.getTimeInMillis() / 1000;
	}

	/**
	 * double 保留2位小数，四舍五入
	 * @param d 要四舍五入的原本的Double
	 * @return 保留2位小数的double
	 */
	public static double doubleSplit(double d){
		double dou = d * 100;
		return (Math.round(dou)+0.0)/100;
	}

	public static Long getDayZoreTime4Linux(){
		return null;
	}

	public static String AppUtilFilter(String str){
		if(str == null || str.length() == 0){
			return "";
		}
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<str.length();i++){
			int ch = str.charAt(i);
			int min = Integer.parseInt("E001", 16);
			int max = Integer.parseInt("E537", 16);
			if(ch >= min && ch <= max){
				sb.append("");
			}else{
				sb.append((char)ch);
			}
		}
		return sb.toString();
	}

	/**
	 * 过滤昵称特殊表情
	 */
	public static String filterName(String name) {
		if(name==null){
			return null;

		}
		if("".equals(name.trim())){
			return "";
		}

		Pattern patter = Pattern.compile("[a-zA-Z0-9\u4e00-\u9fa5]");
		Matcher match = patter.matcher(name);

		StringBuffer buffer = new StringBuffer();

		while (match.find()) {
			buffer.append(match.group());
		}

		return buffer.toString();
	}

	/**
	 * 将object对象转换为int，null时返回0
	 * @author 李鑫
	 * @param object 转换的object对象
	 * @return
	 */
	public static Integer objectToInt(Object object) {
		if (object != null) {
			return Integer.parseInt(String.valueOf(object));
		}else {
			return 0;
		}
	}

	/**
	 * 助力用户注册成功回调
	 * @author 秦艺文
	 * @param userId    用户ID
	 * @param phone 	用户注册手机号
	 */
	public static void returnUserInfo(Integer userId, String phone) {
		HttpUtil httpUtil = new HttpUtil();
		Map<String, String> map = new HashMap<String, String>();
		map.put("userId", userId + "");
		map.put("phone", phone);
		HttpResponse response = httpUtil.post("http://" + Global.get("APPUTIL_SEND_URL") + "/app/share/addPercentage.do", map);
		if (response.getCode() - 200 != 0) {
			response = httpUtil.post("http://" + Global.get("APPUTIL_SEND_URL") + "/app/share/addPercentage.do", map);
			if (response.getCode() - 200 != 0) {
				response = httpUtil.post("http://" + Global.get("APPUTIL_SEND_URL") + "/share/general/addPercentage.do", map);
			}
		}
	}

	/**
	 * 获取本月第一天
	 * @return int 本月第一天的零点的时间戳
	 */
	public static int getMonthStartTime(){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
		int timestamp = (int) (calendar.getTimeInMillis() / 1000);
		return timestamp;
	}

	/**
	 * 获取本月最后一天
	 * @return int 本月最后一天的零点的时间戳
	 */
	public static int getMonthEndTime(){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		int timestamp = (int) (calendar.getTimeInMillis() / 1000);
		return timestamp;
	}

	/**
	 * 获取今天凌晨时间
	 * @return int 10位时间戳
	 */
	public static int getTodayMorningTimestamp() {
		int nowTime = DateUtil.timeForUnix10();
		return DateUtil.getDateZeroTime(nowTime);
	}

	/**
	 * 获取今天午夜时间（23:59:59）
	 * @return int 10位时间戳
	 */
	public static int getTodayMidnightTimestamp() {
		return (getTodayMorningTimestamp() + 86399);
	}

	/**
	 * @param dateStr	十位数时间戳
	 * @param format	日期格式,例如: yyyyMMdd
	 * 获取本月最后一天
	 * @return int yyyyMMdd
	 */
	public static int getMonthLastDay(int dateStr,String formatString) {
		Calendar c = Calendar.getInstance();
		Date date = new Date();
		date.setTime((long)dateStr * 1000);
		c.setTime(date);
		c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
		SimpleDateFormat format = new SimpleDateFormat(formatString);
		String last = format.format(c.getTime());
		return Integer.valueOf(last);
	}


	/**
	 * 获取指定日期下个月的第一天
	 * @param dateStr	指定日期,例如: 20211231
	 * @param format	日期格式,例如: yyyyMMdd
	 * @return
	 */
	public static String getFirstDayOfNextMonth(String dateStr,String format){
		SimpleDateFormat sdf = new SimpleDateFormat(format); 
		try {
			Date date = sdf.parse(dateStr);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.set(Calendar.DAY_OF_MONTH,1);
			calendar.add(Calendar.MONTH, 1);
			return sdf.format(calendar.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取某年第一天日期
	 * @param year 年份
	 * @return Date
	 */

	public static String getYearFirst(int year,String format){
		SimpleDateFormat sdf = new SimpleDateFormat(format); 
		Calendar calendar = Calendar.getInstance();
		calendar.clear();
		calendar.set(Calendar.YEAR, year);
		Date currYearFirst = calendar.getTime();
		return sdf.format(currYearFirst);
	}

	
	/**
	 * 计算两个日期之间相差的天数 
	 * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @param format	日期格式,例如: yyyyMMdd
     * @return 相差天数
	 */
	public static int daysBetween(String smdate,String bdate,String format) throws ParseException{
		SimpleDateFormat sdf=new SimpleDateFormat(format);
		Calendar cal = Calendar.getInstance();  
		cal.setTime(sdf.parse(smdate));  
		long time1 = cal.getTimeInMillis();               
		cal.setTime(sdf.parse(bdate));  
		long time2 = cal.getTimeInMillis();       
		long between_days = (time2-time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));   
	}
	
	/**
	 * 判断字符串是否是数字
	 * @param str 传入的字符串
	 * @return true/false
	 */
	public static boolean isInteger(String str) {  
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
        return pattern.matcher(str).matches();  
  }
	
}
